<template>
  <div class="dialog-overlay" v-if="visible" @click.self="closeDialog">
    <div class="dialog-content modal-main">
      <div class="dialog-header modal-header">
        <h1 class="dialog-title">保存回放任务</h1>
        <button class="close-button" @click="closeDialog">
          <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
            <line x1="18" y1="6" x2="6" y2="18"></line>
            <line x1="6" y1="6" x2="18" y2="18"></line>
          </svg>
        </button>
      </div>
      <div style=" padding:30px; display: flex; align-items: center; flex: 1; position: relative;">
          <label class="form-label required">任务名称</label>
          <input
              type="text"
              class="form-input"
              v-model="taskName"
              placeholder="请输入任务名称"
              :class="{'error': taskNameError}"
              required
              :onchange="handleChange"
              maxlength="50"
              style="margin-left: 10px;"
          >
          <span v-if="taskNameError" class="error-message">必填输入</span>
        </div>
      <div class="dialog-footer modal-footer">
        <button class="tech-btn cancel-btn" @click="closeDialog">取消</button>
        <button class="tech-btn confirm-btn" @click="handleConfirm">确认</button>
      </div>
    </div>
  </div>
  <div v-if="showConfirmDialog" class="confirm-dialog-overlay">
    <div class="confirm-dialog">
      <div class="confirm-dialog-content modal-main">
        <h2 class="confirm-dialog-title modal-header">确认覆盖</h2>
        <p class="confirm-dialog-text">是否确认覆盖已有任务？</p>
        <div class="confirm-dialog-buttons modal-footer">
          <button class="tech-btn cancel-btn" @click="cancelConfirm">取消</button>
          <button class="tech-btn confirm-btn" @click="confirmOverwrite">确定</button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import {defineEmits,onMounted, watch, ref} from 'vue'
import API  from './playbackTask.api.ts';
const mode = localStorage.getItem('mode')
const showConfirmDialog = ref(false)
const props = defineProps<{
  visible: boolean
  selecteSaveParame: Array<{ id: string; name: string; type?: string }>
  viewSettings: any
}>()

const emit = defineEmits<{
  (e: 'update:visible', value: boolean): void;
  (e: 'confirm', value: { name: string; description: string }): void;
  (e: 'success', value: { type: string; content: string; duration: number }): void;
}>()
const taskName = ref('');
const taskNameError = ref(false);
const closeDialog = () => {
  emit('update:visible', false)
  taskName.value = ''
}

// 返回true表示可以添加，不存在。 false 表示存在不可添加
async function taskNameCheck(name: string): Promise<boolean> {
  try {
    const res = await API.taskNameCheck(name);
    return res.data === false;
  } catch (error) {
    console.error('检查任务名称时出错:', error);
    return false;
  }
}

function showTaskName(name: string) {
  taskName.value = name
}

function handleChange() {
  if (!taskName.value.trim()) {
    taskNameError.value = true
    return
  }
  if (taskName.value.length > 50) {
    taskNameError.value = true
    return
  }
  taskNameError.value = false
}

const handleConfirm = async () => {
  if (!taskName.value.trim()) {
    taskNameError.value = true
    return
  }
  // 检查任务名是否已存在
  const exists = await taskNameCheck(taskName.value);
  if (!exists) {
    showConfirmDialog.value = true;
  } else {
    saveTaskFun();
  }
}
// 新增
const saveTaskFun  = () => {
  let params: any = {
    name: taskName.value,
    parameters: JSON.stringify(props.selecteSaveParame)
  }
  if (mode === 'online') {
    params.userId = localStorage.getItem('userId')
  }
  // 保存视图设置
  const viewSet = { ... props.viewSettings }
  // 只提取viewSet中leftA 删除其他对象
  const viewSetParams = Object.keys(viewSet).filter(key => key.includes('leftA'))
  const viewSetParamsObj: any = {}
  viewSetParams.forEach(key => {
    viewSetParamsObj[key] = viewSet[key]
  })
  params.viewSettings = JSON.stringify(viewSetParamsObj)
  try {
    API.saveTask(params).then((res:any) => {
      if (res && res.code == 200) {
        emit('success', {type: 'success', content: '保存成功', duration: 500});
        showConfirmDialog.value = false;
        closeDialog();
      } else {
        emit('success', {type: 'error', content: res.message || '保存失败', duration: 500});
      }
    })
  } catch (error) {
    emit('success', {type: 'error', content: '保存失败，请稍后重试', duration: 500});
  }
}
// 覆盖
const updateTaskFun = () => {
  let params: any = {
    name: taskName.value,
    parameters: JSON.stringify(props.selecteSaveParame)
  }
  if (mode === 'online') {
    params.userId = localStorage.getItem('userId')
  }
  // 保存视图设置
  const viewSet = { ... props.viewSettings }
  // 只提取viewSet中leftA 删除其他对象
  const viewSetParams = Object.keys(viewSet).filter(key => key.includes('leftA'))
  const viewSetParamsObj: any = {}
  viewSetParams.forEach(key => {
    viewSetParamsObj[key] = viewSet[key]
  })
  params.viewSettings = JSON.stringify(viewSetParamsObj)
  API.updateTask(params).then((res:any) => {
    if (res && res.code) {
      emit('success', {type: 'success', content: '覆盖成功！', duration: 500});
      closeDialog();
    } else {
      emit('success', {type: 'error', content: '后台服务有误', duration: 500});
    }
  })
}
// 取消
const cancelConfirm = () => {
  showConfirmDialog.value = false
}
// 确定覆盖
const confirmOverwrite = () => {
  updateTaskFun()
}

defineExpose({
  showTaskName
})

</script>

<style scoped>
.dialog-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}

.dialog-content {
  //background: white;
  border-radius: 12px;
  width: 50%;
  max-width: 600px;
  //box-shadow: 0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -2px rgba(0, 0, 0, 0.05);
  padding: 0;
}

.dialog-header {
  padding: 20px 24px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.dialog-title {
  margin: 0;
  font-size: 18px;
  font-weight: 600;
  color: var(--text-color);
}
.dialog-title {
  color: var(--text-color);
}
.close-button {
  background: none;
  border: none;
  padding: 4px;
  cursor: pointer;
  color: var(--text-color);
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 4px;
}
.close-button:hover{
    color: var(--global-color-black);
    background: none;
}

.form-label {
  font-size: 14px;
  font-weight: 600;
  color: var(--text-color);
  min-width: 40px;
}

.form-label.required::after {
  content: '*';
  color: var(--error-color);
  margin-left: 4px;
}

.form-input {
  width: 80%;
  padding: 8px 12px;
  border: 1px solid var(--input-border-color);
  border-radius: 4px;
  font-size: 14px;
  color: var(--text-color);
  background: var(--input-background);
}
.form-input::placeholder{
  color: var(--preview-text-color)
}
.form-input.error {
  border-color: var(--error-color);
}

.error-message {
  color: var(--error-color);
  font-size: 12px;
  position: absolute;
  bottom: -1px;
  left: 105px;
}

.form-input:focus {
  outline: none;
  border-color: #3b82f6;
  box-shadow: 0 0 0 2px rgba(59, 130, 246, 0.1);
}

.dialog-footer {
  padding: 16px 20px;
  display: flex;
  justify-content: flex-end;
  gap: 20px;
}

.tech-btn {
  height: 36px;
  font-size: 0.875rem;
  padding: 0.35rem 0.75rem;
  border-radius: 0.375rem;
  cursor: pointer;
  transition: all 0.2s ease;
}

.cancel-btn {
  border: 1px solid var(--error-color) !important;
  color: var(--error-color) !important;
}

.cancel-btn:hover {
  background: var(--error-color);
}


/* 确认覆盖弹窗样式 */
.confirm-dialog-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.3);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1050;
}

.confirm-dialog {
  position: relative;
  background: white;
  border-radius: 12px;
  //padding: 24px;
  width: 400px;
  box-shadow: 0 8px 16px rgba(0, 0, 0, 0.15);
  z-index: 1100;
  transform: scale(1);
  transition: transform 0.2s ease;
}

.confirm-dialog-content {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.confirm-dialog-title {
  font-size: 18px;
  font-weight: 600;
  color: var(--text-color);
  margin: 0;
}

.confirm-dialog-text {
  color: var(--text-color);
  margin-left: 20px;
}

.confirm-dialog-buttons {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

@media (max-width: 1024px) {
  .dialog-content {
    width: 85% !important;
    max-width: 500px !important;
  }

  .dialog-header {
    padding: 16px 20px !important;
  }

  .dialog-title {
    font-size: 14px !important;
  }

  .close-button {
    padding: 3px !important;
  }

  .close-button svg {
    width: 16px !important;
    height: 16px !important;
  }

  .form-label {
    font-size: 12px !important;
    min-width: 35px !important;
  }

  .form-input {
    width: 75% !important;
    padding: 6px 10px !important;
    font-size: 13px !important;
    height: 28px !important;
  }

  .error-message {
    font-size: 11px !important;
    left: 90px !important;
  }

  .dialog-footer {
    padding: 12px 16px !important;
    gap: 16px !important;
  }

  .tech-btn {
    padding: 6px 12px !important;
    font-size: 13px !important;
    height: 28px !important;
  }

  .confirm-dialog {
    width: 320px !important;
    //padding: 20px ;
  }

  .confirm-dialog-title {
    font-size: 16px !important;
  }

  .confirm-dialog-text {
    font-size: 13px !important;
  }

  .confirm-dialog-content {
    gap: 16px !important;
  }

  .confirm-dialog-buttons {
    gap: 10px !important;
  }

  .confirm-dialog-buttons .tech-btn {
    padding: 6px 12px !important;
    font-size: 13px !important;
  }
}

</style>
